<template>
    <el-dialog class="get-location-com" :visible.sync="dialogVisible" width="1000px" append-to-body custom-class="location-dialog" :show-close="false">
        <template slot="title">
            <i class="el-icon-error" @click="handleClose"></i>
        </template>
        <div class="address-content-wrap">
            <div :id="'get-location' + _uid" style="width: 100%; height: 720px"></div>
            <div v-if="!isDetail && mapLoadOver" class="search-input">
                <div class="search-input-label">位置名称</div>
                <el-input
                    id="searchInput"
                    v-model="place"
                    class="search-input-value"
                    clearable
                    placeholder="请输入关键字进行搜索"
                    @input="poiSearch"
                ></el-input>
                <ul v-if="addressArr.length !== 0" class="recommend">
                    <li v-for="(start, index) in addressArr" :key="index" class="recommend-item" @click="handleSelect(start)">
                        {{ start.name }}
                    </li>
                </ul>
            </div>
            <div v-if="!isDetail && mapLoadOver" class="action-bar">
                <div class="draw-btn">
                    <el-tooltip v-for="item in vectorgraph" :key="item.type" class="item" :content="item.name" placement="bottom">
                        <IconSvg
                            :icon-class="item.icon"
                            class="btn"
                            :class="{ actived: currentType === item.type, disabled: type !== item.type && type !== 'all' || lngAndLat }"
                            :style="{ 'z-index': currentType === item.type ? '100' : '10' }"
                            @click="handleDraw(item.type)"
                        />
                    </el-tooltip>
                </div>
                <div class="edit-btn">
                    <el-tooltip class="item" content="编辑" placement="bottom">
                        <i
                            class="btn el-icon-edit-outline"
                            style="z-index: 100; position: relative"
                            :class="{ actived: isEdit, disabled: type === 'point' || currentType === 'point' }"
                            @click="handleEdit"
                        ></i>
                    </el-tooltip>
                    <el-tooltip class="item" content="清除" placement="bottom">
                        <i class="btn el-icon-delete" @click="handleClear"></i>
                    </el-tooltip>
                </div>
            </div>

            <div class="botom-panel">
                <input class="text" :value="`经纬度 | ${lngAndLat}`" disabled />
                <div class="button" @click="getlatandlng">确认</div>
            </div>
        </div>
    </el-dialog>
</template>

<script>
import { mapKey } from '@/config/settings'
import AMapLoader from '@amap/amap-jsapi-loader'
import locationIcon from '@/assets/images/location-icon.png'
import markIcon from '@/assets/images/mark-bs.png'

export default {
    name: 'GetMapLocation',
    data() {
        return {
            markIcon,
            locationIcon,
            mapLoadOver: false,
            isLoading: false,
            dialogVisible: false,
            mapLoading: true,
            map: null,
            AMap: null,
            place: '',
            addressArr: [],
            makeMarker: null,
            lngAndLat: '',
            type: 'point', // 可以支持编辑的矢量类型，现在只有单独的点和点线面都可以，2种情况
            currentType: 'point', // 默认选中矢量类型
            vectorgraph: [
                {
                    type: 'point',
                    icon: 'point',
                    name: '点'
                },
                {
                    type: 'line',
                    icon: 'line',
                    name: '线'
                },
                {
                    type: 'surface',
                    icon: 'surface',
                    name: '面'
                }
            ],
            mouseTool: null,
            overlays: [],
            path: [],
            polyEditor: {},
            isEdit: false,
            covering: null,
            isDetail: false
        }
    },
    beforeDestroy() {
        this.map && this.map.destroy()
    },
    methods: {
        handleEdit() {
            // 如果没有绘制图形，编辑不生效
            console.log(this.overlays.length === 0)
            console.log(this.covering === null)
            if (this.overlays.length === 0 && this.covering === null) {
                this.draw(this.currentType)
                return
            }
            // 如果是编辑状态，再次点击关闭编辑
            if (this.isEdit) {
                this.polyEditor.close()
                this.lngAndLat = this.polyEditor?.getTarget()?.getPath().join(';').toString() || ''
                this.draw(this.currentType)
            } else {
                // 编辑时，先关闭鼠标绘制功能。编辑的对象可能是鼠标绘制对象，或者是回填的绘制对象
                this.mouseTool.close()
                this.polyEditor = new this.AMap.PolylineEditor(this.map, (this.overlays[0] || this.covering))
                this.polyEditor.setTarget((this.overlays[0] || this.covering))
                this.polyEditor.open()
            }
            this.isEdit = !this.isEdit
        },
        handleDraw(currentType) {
            // 如果当前只是点、线、面中的其中一种，或点击的是相同类型，或者经纬度已经有值，点击不生效
            if (this.type !== currentType && this.type !== 'all' || this.lngAndLat) {
                return
            }
            // this.handleClear()
            this.mouseTool.close(true)
            this.currentType = currentType
            this.draw(currentType)
        },

        draw(type) {
            const mouseTool = this.mouseTool
            console.log(type)
            switch (type) {
                case 'point': {
                    mouseTool.marker({
                        icon: this.locationIcon,
                        offset: new this.AMap.Pixel(-14, -38)
                    })
                    break
                }
                case 'line': {
                    mouseTool.polyline({
                        strokeColor: '#0062ff'
                        // 同Polyline的Option设置
                    })
                    break
                }
                case 'surface': {
                    mouseTool.polygon({
                        fillColor: '#00b0ff',
                        strokeColor: '#0062ff'
                        // 同Polygon的Option设置
                    })
                    break
                }
            }
        },
        handleClear() {
            // 如果是编辑状态，关闭编辑功能
            if (this.isEdit) {
                this.polyEditor.close()
                this.isEdit = false
            }
            this.covering && this.map.remove(this.covering)
            this.covering = null
            this.map.remove(this.overlays)
            this.overlays = []
            this.lngAndLat = ''
            // 清除后要开启鼠标绘制模式，详情页回填情况下this.mouseTool不存在，要做下判断
            this.mouseTool && this.draw(this.currentType)
        },
        // 桩号检索
        // poi检索
        poiSearch() {
            const autoComplete = new this.AMap.AutoComplete()
            autoComplete.search(this.place, (status, result) => {
                if (status === 'complete' && result) {
                    this.addressArr = result.tips
                } else if (!this.place) {
                    // 请求会存在延时问题
                    this.addressArr = []
                } else {
                    if (document.getElementsByClassName('el-message--warning').length === 0) {
                        this.$message({
                            showClose: true,
                            message: '暂无查询结果，请输入其他地点查询！',
                            type: 'warning'
                        })
                    }
                }
            })
        },
        // 检索选中事件
        handleSelect(val) {
            if (val.id) {
                // 如果之前有标记点先移除
                this.makeMarker && this.map.remove(this.makeMarker)

                const { lng, lat } = val.location
                // this.lngAndLat = lng + ',' + lat
                this.place = val.name
                this.addressArr = []

                // 增加新的标记点
                this.addMakeMarker(lng, lat)
                // 设置地图中心点
                this.map.setCenter([lng, lat])
            } else {
                this.$message({
                    message: '请选择具体的位置！',
                    type: 'warning'
                })
            }
        },
        // 地图初始化
        init(position, currentType) {
            const option = {
                key: mapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
                version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ['AMap.AutoComplete', 'AMap.MouseTool', 'AMap.PolylineEditor', 'AMap.Polyline', 'AMap.Polygon'],
                resizeEnable: true, // 是否监控地图容器尺寸变化
                viewMode: '2D'
            }
            AMapLoader.load(option)
                .then((AMap) => {
                    this.AMap = AMap
                    this.map = new AMap.Map('get-location' + this._uid, { zoom: 12 })
                    this.mapLoadOver = true
                    if (position.length > 0) {
                        let covering = {}
                        if (currentType === 'point') {
                            covering = new this.AMap.Marker({
                                position: new this.AMap.LngLat(position[0], position[1]),
                                icon: this.locationIcon,
                                offset: new this.AMap.Pixel(-14, -40)
                            })
                        } else if (currentType === 'line') {
                            covering = new AMap.Polyline({
                                path: position,
                                strokeColor: '#0062ff'
                            })
                        } else if (currentType === 'surface') {
                            covering = new AMap.Polygon({
                                path: position,
                                fillColor: '#00b0ff',
                                strokeColor: '#0062ff'
                            })
                        }
                        this.covering = covering
                        this.map.add(covering)
                        this.map.setZoom(16)
                        this.map.setFitView()
                    }
                    // 如果是详情页，不进行绘制
                    if (this.isDetail) { return }

                    this.mouseTool = new AMap.MouseTool(this.map)
                    this.draw(this.currentType)
                    this.mouseTool.on('draw', (e) => {
                        // 绘制完毕清空上一个图形
                        this.handleClear()
                        this.overlays.push(e.obj)
                        // 绘制点和绘制线面获取坐标方式不一样
                        if (e.obj.type === 'AMap.Marker') {
                            const { lng, lat } = e.obj._position
                            this.path = [lng, lat]
                            this.lngAndLat = lng + ',' + lat
                        } else {
                            this.path = e.obj.getPath()
                            this.lngAndLat = this.path.join(';').toString()
                        }
                    })
                })
                .catch((e) => {
                    console.log(e)
                })
        },

        // 添加手动标记点
        addMakeMarker(lng, lat) {
            // 增加新的标记点
            this.makeMarker = new this.AMap.Marker({
                position: new this.AMap.LngLat(lng, lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                icon: this.markIcon,
                offset: new this.AMap.Pixel(-14, -40)
            })
            this.map.add(this.makeMarker)
        },
        // 显示弹框
        show(lnglat, type, currentType, isDetail) {
            this.type = type || 'point'
            this.currentType = currentType || 'point'
            this.isDetail = isDetail
            this.dialogVisible = true
            this.lngAndLat = lnglat || ''
            let position = []
            if (lnglat) {
                if (this.currentType === 'point') {
                    position = lnglat.split(',')
                    if (position.length !== 2) {
                        position = []
                    }
                } else {
                    position = lnglat.split(';').map(item => item.split(','))
                }
            }
            this.$nextTick(() => {
                this.init(position, this.currentType)
            })
        },
        getlatandlng() {
            if (!this.isDetail) {
                // 编辑状态下处理经纬度
                this.isEdit && (this.lngAndLat = this.polyEditor?.getTarget()?.getPath().join(';').toString() || '')
                console.log(this.currentType)
                this.$emit('location', { value: this.lngAndLat, type: this.currentType })
            }
            this.handleClose()
        },
        handleClose() {
            this.handleClear()
            this.dialogVisible = false
        }
    }
}
</script>

<style lang="scss">
.location-dialog {
    .el-dialog__header {
        position: absolute;
        z-index: 10;
        text-align: right;
        padding: 0px;
        top: 33px;
        right: 49px;
        font-size: 26px;
        color: #999;
        line-height: 26px;
        height: 26px;
        cursor: pointer;
    }
    .el-dialog__body {
        padding: 0;
    }
}
</style>

<style lang="scss" scoped>
.address-content-wrap {
    position: relative;
    width: 100%;
    overflow: hidden;
    ::v-deep .el-input__validateIcon {
        display: none;
    }
    .action-bar {
        position: absolute;
        top: 32px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        align-items: center;
        .draw-btn {
            display: flex;
            margin-right: 16px;
            .btn {
                font-size: 20px;
                padding: 5px;
                position: relative;
            }
        }
        .btn {
            border: 1px solid #dcdfe6;
            background-color: #fff;
            padding: 4px;
            font-size: 22px;
            color: #606266;
            box-sizing: content-box;
            cursor: pointer;
            &:hover {
                color: #409eff;
                background-color: #ecf5ff;
                border-color: #b3d8ff;
            }
            &.disabled {
                cursor: not-allowed;
                background-color: #ebedf3;
                &:hover {
                    color: #606266;
                    background-color: #ebedf3;
                    border-color: #dcdfe6;
                }
            }

            &.actived {
                color: #409eff;
                background-color: #ecf5ff;
                border-color: #b3d8ff;
            }
        }
        .btn + .btn {
            margin-left: -1px;
        }
    }
    .search-input {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        position: absolute;
        top: 32px;
        left: 35px;
        .search-input-label {
            flex-shrink: 0;
            height: 36px;
            line-height: 36px;
            margin-right: 8px;
            font-size: 14px;
            color: #000;
        }
        .search-input-value {
            width: 220px;
            height: 36px;
        }
        .recommend {
            width: 220px;
            position: absolute;
            top: 36px;
            right: 0;
            background-color: #fff;
            border: 1px solid #d1d1d1;
            .recommend-item {
                font-size: 11px;
                color: #44444f;
                padding: 8px 12px;
                cursor: pointer;
                &:hover {
                    background-color: rgba(0, 98, 255, 0.06);
                }
            }
        }
        ::v-deep .el-input-group__append {
            background-color: #5474fb;
            border-color: #5474fb;
            i {
                color: #fff;
            }
        }
        ::v-deep .el-input__inner {
            color: #000;
        }
    }
    .botom-panel {
        position: absolute;
        left: 50%;
        bottom: 32px;
        box-sizing: border-box;
        transform: translateX(-50%);
        background: #fff;
        border: 1px solid #e2e2e2;
        border-radius: 5px 0 0 5px;
        display: flex;
        .text {
            width: 304px;
            height: 36px;
            line-height: 36px;
            padding: 0 16px;
            outline: none;
        }
        .button {
            width: 67px;
            height: 36px;
            line-height: 36px;
            text-align: center;
            background-color: #0062ff;
            color: #fff;
            border-radius: 0 5px 5px 0;
            cursor: pointer;
        }
    }
}
::v-deep {
    .amap-logo {
        display: none !important;
        visibility: hidden !important;
    }
    .amap-copyright {
        display: none !important;
        visibility: hidden !important;
    }
    .amap-info-content {
        background: #222;
        color: #1a1d24;
        font-size: 14px;
        border-radius: 5px;
        padding-left: 18px;
    }
    .bottom-center .amap-info-sharp {
        border-top: 8px solid #222;
    }
    .amap-info-close {
        display: none !important;
    }
}
</style>
